package com.aimosheng.main.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aimosheng.common.CommonAppConfig;
import com.aimosheng.common.Constants;
import com.aimosheng.common.activity.AbsActivity;
import com.aimosheng.common.http.HttpCallback;
import com.aimosheng.common.interfaces.ActivityResultCallback;
import com.aimosheng.common.interfaces.CommonCallback;
import com.aimosheng.common.interfaces.ImageResultCallback;
import com.aimosheng.common.upload.FileUploadManager;
import com.aimosheng.common.upload.UploadBean;
import com.aimosheng.common.upload.UploadCallback;
import com.aimosheng.common.upload.UploadStrategy;
import com.aimosheng.common.utils.ClickUtil;
import com.aimosheng.common.utils.DialogUitl;
import com.aimosheng.common.utils.L;
import com.aimosheng.common.utils.ProcessImageUtil;
import com.aimosheng.common.utils.StringUtil;
import com.aimosheng.common.utils.ToastUtil;
import com.aimosheng.common.utils.WordUtil;
import com.aimosheng.main.R;
import com.aimosheng.main.adapter.AuthImageAdapter;
import com.aimosheng.main.custom.UploadImageView;
import com.aimosheng.main.utils.CityUtil;
import com.aimosheng.one.bean.ImpressBean;
import com.aimosheng.one.custom.ImpressGroup;
import com.aimosheng.one.dialog.ChooseImpressDialogFragment;
import com.aimosheng.one.http.OneHttpConsts;
import com.aimosheng.one.http.OneHttpUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.qqtheme.framework.entity.City;
import cn.qqtheme.framework.entity.County;
import cn.qqtheme.framework.entity.Province;
import cn.qqtheme.framework.picker.AddressPicker;
import cn.qqtheme.framework.picker.OptionPicker;

/**
 * Created by cxf on 2019/4/9.
 */

public class AuthActivity extends AbsActivity implements ChooseImpressDialogFragment.ActionListener {

    public static void forward(Context context, int authStauts, int sex) {
        Intent intent = new Intent(context, AuthActivity.class);
        intent.putExtra(Constants.AUTH_STATUS, authStauts);
        intent.putExtra(Constants.MAIN_SEX, sex);
        context.startActivity(intent);
    }

    private static final String TAG = "AuthActivity";
    private ProcessImageUtil mImageUtil;
    private UploadImageView mCover;
    private int mTargetPositon;
    private RecyclerView mRecyclerView;
    private AuthImageAdapter mAdapter;
    private Dialog mChooseImageDialog;
    private ActivityResultCallback mChooseImageCallback;

    private EditText mName;//姓名
    private EditText mPhoneNum;//手机号
    private EditText mHeight;//身高
    private EditText mWeight;//体重
    private TextView mSex;//性别
    private TextView mStar;//星座
    private ImpressGroup mImpressGroup;//形象标签
    private View mImpressTip;//形象标签提示
    private TextView mCity;//城市
    private EditText mIntro;//介绍
    private EditText mSign;//个性签名
    private TextView mIntroNum;//介绍 字数
    private TextView mSignNum;//个性签名 字数

    private Integer[] mSexArray;
    private String[] mStarArray;

    private String mNameVal;
    private String mPhoneNumVal;
    private String mHeightVal;
    private String mWeightVal;
    private Integer mSexVal;
    private String mStarVal;
    private String mImpressVal;
    private String mProvinceVal;
    private String mCityVal;
    private String mZoneVal;
    private String mIntroVal;
    private String mSignVal;

    private UploadBean mCoverUploadBean;
    private List<UploadBean> mUploadList;
    private UploadStrategy mUploadStrategy;
    private Dialog mLoading;
    private int mAuthStatus;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_auth;
    }

    @Override
    protected void main() {
        setTitle(WordUtil.getString(R.string.auth_my_auth));
        mAuthStatus = getIntent().getIntExtra(Constants.AUTH_STATUS, Constants.AUTH_NONE);
        mSexVal = getIntent().getIntExtra(Constants.MAIN_SEX, 2);
        mImageUtil = new ProcessImageUtil(this);
        mImageUtil.setImageResultCallback(new ImageResultCallback() {
            @Override
            public void beforeCamera() {

            }

            @Override
            public void onSuccess(File file) {
                if (file == null) {
                    return;
                }
                if (mTargetPositon < 0) {
                    if (mCover != null) {
                        mCoverUploadBean.setOriginFile(file);
                        mCover.showImageData(mCoverUploadBean);
                    }
                } else {
                    if (mAdapter != null) {
                        mAdapter.updateItem(mTargetPositon, file);
                    }
                }
            }

            @Override
            public void onFailure() {
            }
        });
        mCover = findViewById(R.id.cover);
        mCover.setActionListener(new UploadImageView.ActionListener() {
            @Override
            public void onAddClick(UploadImageView uploadImageView) {
                chooseImage(-1);
            }

            @Override
            public void onDelClick(UploadImageView uploadImageView) {
                if (mCoverUploadBean != null && mCover != null) {
                    mCoverUploadBean.setEmpty();
                    mCover.showImageData(mCoverUploadBean);
                }
            }
        });
        mRecyclerView = findViewById(R.id.recyclerView);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        mAdapter = new AuthImageAdapter(mContext);
        mRecyclerView.setAdapter(mAdapter);

        mName = findViewById(R.id.name);//姓名
        mPhoneNum = findViewById(R.id.phone_num);//手机号
        mHeight = findViewById(R.id.height);//身高
        mWeight = findViewById(R.id.weight);//体重
        mSex = findViewById(R.id.sex);//性别
        mStar = findViewById(R.id.star);//星座
        mImpressGroup = findViewById(R.id.impress_group);//形象标签
        mImpressTip = findViewById(R.id.impress_tip);
        mCity = findViewById(R.id.city);//城市
        mIntro = findViewById(R.id.intro);//介绍
        mSign = findViewById(R.id.sign);//个性签名
        mIntroNum = findViewById(R.id.intro_num);//介绍 字数
        mSignNum = findViewById(R.id.sign_num);//个性签名 字数
        if (mAuthStatus == 1) {
            findViewById(R.id.photo_group).setVisibility(View.GONE);
        }

        if (mSex != null) {
            mSex.setText(mSexVal == 1 ? R.string.sex_male : R.string.sex_female);
        }

        mIntro.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mIntroNum != null) {
                    mIntroNum.setText(s.length() + "/40");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mSign.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mSignNum != null) {
                    mSignNum.setText(s.length() + "/40");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mCoverUploadBean = new UploadBean();
        getAuthInfo();
    }

    public void authClick(View v) {
        if (!ClickUtil.canClick()) {
            return;
        }
        int i = v.getId();
        if (i == R.id.btn_city) {
            chooseCity();
        } else if (i == R.id.btn_star) {
            chooseXinZuo();
        } else if (i == R.id.btn_sex) {
            chooseSex();
        } else if (i == R.id.btn_impression) {
            chooseImpress();
        } else if (i == R.id.btn_submit) {
            submit();
        }
    }

    /**
     * 选择图片
     */
    public void chooseImage(int targetPositon) {
        mTargetPositon = targetPositon;
        if (mChooseImageDialog == null) {
            mChooseImageDialog = DialogUitl.getStringArrayDialog(mContext, new Integer[]{
                    R.string.camera, R.string.alumb}, true, new DialogUitl.StringArrayDialogCallback() {
                @Override
                public void onItemClick(String text, int tag) {
                    if (tag == R.string.camera) {
                        mImageUtil.getImageByCamera(mTargetPositon < 0);
                    } else {
                        if (mTargetPositon < 0) {
                            mImageUtil.getImageByAlumb(true);
                        } else {
//                            if (mChooseImageCallback == null) {
//                                mChooseImageCallback = new ActivityResultCallback() {
//                                    @Override
//                                    public void onSuccess(Intent intent) {
//                                        if (intent != null) {
//                                            List<String> list = intent.getStringArrayListExtra(Constants.SELECT_IMAGE_PATH);
//                                            if (mAdapter != null) {
//                                                mAdapter.insertItem(list);
//                                            }
//                                        }
//                                    }
//                                };
//                            }
//                            mImageUtil.startActivityForResult(new Intent(mContext, ChooseMutiImageActivity.class), mChooseImageCallback);
                            mImageUtil.getImageByAlumb(false);
                        }
                    }
                }
            });
        }
        mChooseImageDialog.show();
    }


    /**
     * 选择性别
     */
    private void chooseSex() {
        if (mSexArray == null) {
            mSexArray = new Integer[]{R.string.sex_male, R.string.sex_female};
        }
        DialogUitl.showStringArrayDialog(mContext, mSexArray, new DialogUitl.StringArrayDialogCallback() {
            @Override
            public void onItemClick(String text, int tag) {
                mSexVal = tag == mSexArray[0] ? 1 : 2;
                if (mSex != null) {
                    mSex.setText(text);
                }
            }
        });
    }


    /**
     * 选择城市
     */
    private void chooseCity() {
        ArrayList<Province> list = CityUtil.getInstance().getCityList();
        if (list == null || list.size() == 0) {
            final Dialog loading = DialogUitl.loadingDialog(mContext);
            loading.show();
            CityUtil.getInstance().getCityListFromAssets(new CommonCallback<ArrayList<Province>>() {
                @Override
                public void callback(ArrayList<Province> newList) {
                    loading.dismiss();
                    if (newList != null) {
                        showChooseCityDialog(newList);
                    }
                }
            });
        } else {
            showChooseCityDialog(list);
        }
    }

    /**
     * 选择城市
     */
    private void showChooseCityDialog(ArrayList<Province> list) {
        String province = mProvinceVal;
        String city = mCityVal;
        String district = mZoneVal;
        if (TextUtils.isEmpty(province)) {
            province = CommonAppConfig.getInstance().getProvince();
        }
        if (TextUtils.isEmpty(city)) {
            city = CommonAppConfig.getInstance().getCity();
        }
        if (TextUtils.isEmpty(district)) {
            district = CommonAppConfig.getInstance().getDistrict();
        }
        DialogUitl.showCityChooseDialog(this, list, province, city, district, new AddressPicker.OnAddressPickListener() {
            @Override
            public void onAddressPicked(Province province, final City city, County county) {
                String provinceName = province.getAreaName();
                String cityName = city.getAreaName();
                String zoneName = county.getAreaName();
                mProvinceVal = provinceName;
                mCityVal = cityName;
                mZoneVal = zoneName;
                if (mCity != null) {
                    mCity.setText(provinceName + cityName + zoneName);
                }
            }
        });
    }

    /**
     * 选择星座
     */
    private void chooseXinZuo() {
        if (mStarArray == null) {
            mStarArray = new String[]{
                    WordUtil.getString(R.string.xingzuo_00),
                    WordUtil.getString(R.string.xingzuo_01),
                    WordUtil.getString(R.string.xingzuo_02),
                    WordUtil.getString(R.string.xingzuo_03),
                    WordUtil.getString(R.string.xingzuo_04),
                    WordUtil.getString(R.string.xingzuo_05),
                    WordUtil.getString(R.string.xingzuo_06),
                    WordUtil.getString(R.string.xingzuo_07),
                    WordUtil.getString(R.string.xingzuo_08),
                    WordUtil.getString(R.string.xingzuo_09),
                    WordUtil.getString(R.string.xingzuo_10),
                    WordUtil.getString(R.string.xingzuo_11)
            };
        }
        DialogUitl.showXinZuoDialog(this, mStarArray, new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int index, String item) {
                if (mStar != null) {
                    mStar.setText(item.substring(0, item.indexOf("(")));
                }
            }
        });
    }

    /**
     * 选择形象标签
     */
    private void chooseImpress() {
        if (mImpressGroup == null) {
            return;
        }
        ChooseImpressDialogFragment fragment = new ChooseImpressDialogFragment();
        fragment.setCheckImpressList(mImpressGroup.getImpressBeanList());
        fragment.setActionListener(this);
        fragment.show(getSupportFragmentManager(), "ChooseImpressDialogFragment");
    }

    @Override
    public void onChooseImpress(List<ImpressBean> list) {
        showImpress(list);
    }

    private void showImpress(List<ImpressBean> list) {
        if (mImpressGroup != null) {
            mImpressGroup.showData(list);
        }
        if (list != null && list.size() > 0) {
            if (mImpressTip != null && mImpressTip.getVisibility() == View.VISIBLE) {
                mImpressTip.setVisibility(View.INVISIBLE);
            }
        } else {
            if (mImpressTip != null && mImpressTip.getVisibility() != View.VISIBLE) {
                mImpressTip.setVisibility(View.VISIBLE);
            }
        }
    }


    /**
     * 提交认证信息
     */
    private void submit() {
        mUploadList = new ArrayList<>();
        if (mCoverUploadBean.isEmpty()) {
            ToastUtil.show(R.string.auth_tip_32);
            return;
        }
        mUploadList.add(mCoverUploadBean);
        if (mAdapter.isEmpty()) {
            ToastUtil.show(R.string.auth_tip_33);
            return;
        }
        List<UploadBean> bgUploadList = mAdapter.getList();
        mUploadList.addAll(bgUploadList);
        mNameVal = mName.getText().toString().trim();
        if (TextUtils.isEmpty(mNameVal)) {
            ToastUtil.show(R.string.auth_tip_22);
            return;
        }
        mPhoneNumVal = mPhoneNum.getText().toString().trim();
        if (TextUtils.isEmpty(mPhoneNumVal)) {
            ToastUtil.show(R.string.auth_tip_23);
            return;
        }
        if (mSexVal == null) {
            ToastUtil.show(R.string.auth_tip_24);
            return;
        }
        mHeightVal = mHeight.getText().toString().trim();
        if (TextUtils.isEmpty(mHeightVal)) {
            ToastUtil.show(R.string.auth_tip_25);
            return;
        }
        mWeightVal = mWeight.getText().toString().trim();
        if (TextUtils.isEmpty(mWeightVal)) {
            ToastUtil.show(R.string.auth_tip_26);
            return;
        }
        mStarVal = mStar.getText().toString().trim();
        if (TextUtils.isEmpty(mStarVal)) {
            ToastUtil.show(R.string.auth_tip_27);
            return;
        }
        List<ImpressBean> impressBeanList = mImpressGroup.getImpressBeanList();
        if (impressBeanList == null || impressBeanList.size() == 0) {
            ToastUtil.show(R.string.auth_tip_28);
            return;
        }
        mImpressVal = "";
        for (int i = 0, size = impressBeanList.size(); i < size; i++) {
            mImpressVal += impressBeanList.get(i).getId();
            if (i < size - 1) {
                mImpressVal += ",";
            }
        }
        String address = mCity.getText().toString().trim();
        if (TextUtils.isEmpty(address)) {
            ToastUtil.show(R.string.auth_tip_29);
            return;
        }
        mIntroVal = mIntro.getText().toString().trim();
        if (TextUtils.isEmpty(mIntroVal)) {
            ToastUtil.show(R.string.auth_tip_30);
            return;
        }
        mSignVal = mSign.getText().toString().trim();
        if (TextUtils.isEmpty(mSignVal)) {
            ToastUtil.show(R.string.auth_tip_31);
            return;
        }
        if (mLoading == null) {
            mLoading = DialogUitl.loadingDialog(mContext);
        }
        mLoading.show();
        uploadFile();
    }

    /**
     * 上传图片
     */
    private void uploadFile() {
        L.e(TAG, "上传图片开始--------->");
        FileUploadManager.getInstance().createUploadImpl(mContext, new CommonCallback<UploadStrategy>() {
            @Override
            public void callback(UploadStrategy strategy) {
                if (strategy == null) {
                    ToastUtil.show(WordUtil.getString(R.string.upload_type_error));
                    return;
                }
                mUploadStrategy = strategy;
                mUploadStrategy.upload(mUploadList, true, new UploadCallback() {
                    @Override
                    public void onFinish(List<UploadBean> list, boolean success) {
                        if (success) {
                            L.e(TAG, "上传图片完成---------> " + success);
                            if (list != null && list.size() > 1) {
                                String thumb = list.get(0).getRemoteFileName();
                                StringBuilder sb = new StringBuilder();
                                if (!TextUtils.isEmpty(list.get(0).getRemoteAccessUrl())) {
                                    //如果有完整链接，则认为是之前发过的图片
                                    thumb = list.get(0).getRemoteAccessUrl();
                                }
                                if (!TextUtils.isEmpty(thumb)) {
                                    thumb = getPrefixUrl(thumb);
                                }
                                for (int i = 1, size = list.size(); i < size; i++) {
                                    String fileName = list.get(i).getRemoteFileName();
                                    if (!TextUtils.isEmpty(list.get(i).getRemoteAccessUrl())) {
                                        //如果有完整链接，则认为是之前发过的图片
                                        fileName = list.get(i).getRemoteAccessUrl();
                                    }
                                    if (!TextUtils.isEmpty(fileName)) {
                                        fileName = getPrefixUrl(fileName);
                                        sb.append(fileName);
                                        sb.append(",");
                                    }
                                }
                                String photos = sb.toString();
                                if (photos.length() > 1) {
                                    photos = photos.substring(0, photos.length() - 1);
                                }
                                doSubmit(thumb, photos);
                            }
                        }
                    }
                });

            }
        });
    }

    // TODO: 2021-01-05 如果服务端返回 完整的连接，替换前缀 保证服务端能判断旧图片存储方式
    private String getPrefixUrl(String completeUrl) {
        if (TextUtils.isEmpty(completeUrl)) {
            return "";
        }
        if (completeUrl.contains("http://") || completeUrl.contains("https://")) {
            String tempStr = completeUrl.substring(0, completeUrl.lastIndexOf(".") + 4);
            String lastName = tempStr.substring(tempStr.lastIndexOf("/") + 1);
            if (completeUrl.contains(Constants.UPLOAD_TYPE_AWS)) {
                completeUrl = Constants.UPLOAD_TYPE_PREFIX_AWS + lastName;
            } else if (completeUrl.contains(Constants.UPLOAD_TYPE_QINIU)) {
                completeUrl = Constants.UPLOAD_TYPE_PREFIX_QINIU + lastName;
            }
            L.e(TAG, "getPrefixUrl--->tempStr-->" + tempStr + " ---fileName--->" + completeUrl);
        }
        return completeUrl;
    }

    private void doSubmit(String thumb, String photos) {
        OneHttpUtil.setAuth(thumb, photos, mNameVal, mPhoneNumVal, mSexVal, mHeightVal, mWeightVal, mStarVal,
                mImpressVal, mProvinceVal, mCityVal, mZoneVal, mIntroVal, mSignVal, new HttpCallback() {
                    @Override
                    public void onSuccess(int code, String msg, String[] info) {
                        if (code == 0) {
                            finish();
                        }
                        ToastUtil.show(msg);
                    }

                    @Override
                    public void onFinish() {
                        if (mLoading != null) {
                            mLoading.dismiss();
                        }
                    }
                }
        );
    }


    private void getAuthInfo() {
        if (mAuthStatus == Constants.AUTH_NONE) {
            return;
        }
        OneHttpUtil.getAuth(new HttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String[] info) {
                if (code == 0 && info.length > 0) {
                    JSONObject obj = JSON.parseObject(info[0]);
                    if (mCover != null) {
                        String thumb = obj.getString("thumb");
                        mCoverUploadBean.setRemoteAccessUrl(thumb);
                        mCoverUploadBean.setRemoteFileName(thumb.substring(thumb.lastIndexOf("/") + 1));
                        mCover.showImageData(mCoverUploadBean);
                    }
                    if (mAdapter != null) {
                        List<String> imageUrlList = JSON.parseArray(obj.getString("photos_list"), String.class);
                        List<UploadBean> bgList = new ArrayList<>();
                        for (String imageUrl : imageUrlList) {
                            UploadBean bean = new UploadBean();
                            bean.setRemoteAccessUrl(imageUrl);
                            bean.setRemoteFileName(imageUrl.substring(imageUrl.lastIndexOf("/") + 1));
                            bgList.add(bean);
                        }
                        mAdapter.setList(bgList);
                    }
                    mNameVal = obj.getString("name");
                    if (mName != null) {
                        mName.setText(mNameVal);
                    }
                    mPhoneNumVal = obj.getString("mobile");
                    if (mPhoneNum != null) {
                        mPhoneNum.setText(mPhoneNumVal);
                    }
                    mSexVal = obj.getIntValue("sex");
                    if (mSex != null) {
                        mSex.setText(mSexVal == 1 ? R.string.sex_male : R.string.sex_female);
                    }
                    mHeightVal = obj.getString("height");
                    if (mHeight != null) {
                        mHeight.setText(mHeightVal);
                    }
                    mWeightVal = obj.getString("weight");
                    if (mWeight != null) {
                        mWeight.setText(mWeightVal);
                    }
                    mStarVal = obj.getString("constellation");
                    if (mStar != null) {
                        mStar.setText(mStarVal);
                    }
                    mProvinceVal = obj.getString("province");
                    mCityVal = obj.getString("city");
                    mZoneVal = obj.getString("district");
                    if (mCity != null) {
                        mCity.setText(StringUtil.contact(mProvinceVal, mCityVal, mZoneVal));
                    }
                    mIntroVal = obj.getString("intr");
                    if (mIntro != null) {
                        mIntro.setText(mIntroVal);
                    }
                    mSignVal = obj.getString("signature");
                    if (mSign != null) {
                        mSign.setText(mSignVal);
                    }
                    List<ImpressBean> impressBeanList = JSON.parseArray(obj.getString("label_list"), ImpressBean.class);
                    showImpress(impressBeanList);
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        OneHttpUtil.cancel(OneHttpConsts.GET_AUTH);
        OneHttpUtil.cancel(OneHttpConsts.SET_AUTH);
        if (mAdapter != null) {
            mAdapter.release();
        }
        if (mImageUtil != null) {
            mImageUtil.release();
        }
        mImageUtil = null;
        super.onDestroy();
    }

}
